import {request} from "vendor/utils/T";
import {toApi} from '@/service/proxyApi';
import {permission} from "@/service/permission";
import { RespDataType, RequestDataType } from "./apiType";

export * from "./apiType";
const {postJSON, get} = request;

/**
 * 获取验证码
 */
export const getCaptchaImage = () => get<RespDataType.ICaptchaImageInfo>(toApi("captchaImage"));

/**
 * 登录
 */
export const login = (params: RequestDataType.LoginParams) => postJSON(toApi("login"), params);   // 新版

/**
 * 退出
 */
export const logout = () => new Promise((resolve, reject) => {
    get(toApi("api/v1/system/logout")).then(() => {
        permission.loginUser.clear()
        resolve(true)
    }).catch((e) => reject(e))
});

/**
 * 检查是否登录
 */
export const checkLogin = (isShowErrorPrompt = true) => new Promise((resolve, reject) => {
    get(toApi("checkLogin"), {}, {isShowErrorPrompt}).then(() => {
        resolve(true)
    }).catch((e) => {
        permission.loginUser.clear()
        reject(e)
    })
});

/**
 * 获取用户信息
 */
export const getUserInfo = () => new Promise((resolve, reject) => {
    get(toApi("getInfo")).then((resp) => {
        const {user} = resp.data;
        permission.loginUser.set({// @ts-ignore
            ...user,
            lat: user.dept.lat,
            lng: user.dept.lng,
            deptType: user.dept.deptType,
            roleType: resp.data.roles.includes('admin') && 'admin',
            permissions: resp.data.permissions
        });
        resolve(true);
    }).catch((e) => {
        permission.loginUser.clear();
        console.error(e);
        reject(e);
    })
});
